package com.xmwzw.catpu;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;

import com.xmwzw.catpu.databinding.ActivityRegisterBinding;
import com.xmwzw.catpu.http.BaseRequest;
import com.xmwzw.catpu.http.bean.BaseRespond;
import com.xmwzw.catpu.http.listener.RegisterListener;
import com.xmwzw.catpu.viewmodel.RegisterViewModel;

import java.lang.ref.WeakReference;

public class RegisterActivity extends BaseActivity {
    private ActivityRegisterBinding registerBinding;
    private RegisterViewModel registerViewModel;
    private MyHandler myHandler;

    @Override
    public int getLayoutId() {
        return R.layout.activity_register;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        registerBinding = getBaseViewBinding();
        registerBinding.setModel(registerViewModel = new RegisterViewModel());
        registerBinding.setClick(new Click());

        myHandler = new MyHandler(this);
    }


    public class Click {
        public void register() {
            String error = registerViewModel.getValidateError();
            if (!TextUtils.isEmpty(error)) {
                showToast(error);
                return;
            }

            BaseRequest.getInstance().register(registerViewModel.mAccount,
                    registerViewModel.mPassword,
                    registerViewModel.mConfirmPaw,
                    new RegisterListener() {
                @Override
                public void getRespond(BaseRespond respond) {
                    Message message = myHandler.obtainMessage();
                    message.what = 1;
                    message.obj = respond;
                    myHandler.sendMessage(message);
                }
            });

        }

        public void back() {
            finish();
        }
    }

    private static class MyHandler extends Handler {
        WeakReference<RegisterActivity> weakReference;

        public MyHandler(RegisterActivity registerActivity) {
            weakReference = new WeakReference<>(registerActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    BaseRespond loginRespond = (BaseRespond) msg.obj;
                    if (loginRespond.code != 0) {
                        weakReference.get().showToast(loginRespond.msg);
                    } else {
                       weakReference.get().showToast("注册成功");
                       weakReference.get().finish();
                    }
                    break;

            }
        }
    }
}
